package com.atguigu.day12;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple1;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;
import org.apache.flink.table.functions.TableFunction;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

public class Flink08_SQL_UDF_AggFun {
    public static void main(String[] args) {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.获取表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //3.从端口读取数据并转为WaterSensor
        SingleOutputStreamOperator<WaterSensor> streamSource = env.socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                });

        //4.将流转为表
        Table table = tableEnv.fromDataStream(streamSource);

        tableEnv.createTemporaryView("sensor",table);

        //不注册直接使用（只能在TableAPI中使用）
  /*      table.groupBy($("id"))
                .select($("id"),call(MyUDAF.class,$("vc")).as("vcSum"))
                .execute()
                .print();*/

        //先注册再使用
        tableEnv.createTemporarySystemFunction("myAvg",MyUDAF.class);
 /*       table.groupBy($("id"))
                .select($("id"),call("myAvg",$("vc")).as("vcSum"))
                .execute()
                .print();*/
        //SQL中使用
        tableEnv.executeSql(
                "select " +
                        "id," +
                        "myAvg(vc) as vcSum " +
                        "from sensor group by id").print();
    }

    //TODO 自定义一个聚合函数 实现avg的功能
    public static class MyUDAF extends AggregateFunction<Double, Tuple2<Integer,Integer>>{

        @Override
        public Tuple2<Integer, Integer> createAccumulator() {
            return Tuple2.of(0,0);
        }

        public void accumulate(Tuple2<Integer,Integer> acc,Integer value){
            acc.f0 += value;
            acc.f1++;
        }

        @Override
        public Double getValue(Tuple2<Integer, Integer> accumulator) {
            return accumulator.f0*1D/accumulator.f1;
        }
    }
}
